package net.asrsmid.connection.as;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import net.asrsmid.config.AsApplication;

import org.apache.commons.pool.PoolableObjectFactory;
import org.olap4j.OlapConnection;
import org.olap4j.OlapWrapper;


/**
 * @author Chen WANG
 * @since 05 May 2011
 */
public class AsOlapConnectionFactory implements PoolableObjectFactory {
	private AsApplication asApp;

	/**
	 * @param asApp
	 */
	public AsOlapConnectionFactory(AsApplication asApp) {
		this.asApp = asApp;
	}

	public AsOlapConnection makeObject() {
		AsOlapConnection asConn = null;
		try {
			Class.forName(asApp.getDriverName());
			String connString = asApp.getOlapConnectionString();
			String user = null;//asApp.getDefaultUserName();
			String password = null;//asApp.getDefaultUserPassword();
			Connection conn = DriverManager.getConnection(connString, user, password);
			OlapWrapper wrapper = (OlapWrapper) conn;
			OlapConnection olapConnection = wrapper.unwrap(OlapConnection.class);
			
			asConn = new AsOlapConnection(olapConnection);
		} catch (ClassNotFoundException e) {
			// driver not found
			e.printStackTrace();
		} catch (SQLException e) {
			// connection establishment error
			e.printStackTrace();
		} catch (Exception e) {
			// other errors
			e.printStackTrace();
		}
	
		return asConn;
	}

	public void activateObject(Object arg0) throws Exception {
	}

	public void destroyObject(Object arg0) throws Exception {
		AsOlapConnection asConn = (AsOlapConnection) arg0;
		OlapConnection conn = asConn.unwrap();
		if (conn != null && !conn.isClosed())
			conn.close();
		asConn = null;
	}

	public void passivateObject(Object arg0) throws Exception {
	}

	public boolean validateObject(Object arg0) {
		AsOlapConnection asConn = (AsOlapConnection) arg0;
		try {
			if (asConn != null && asConn.getMetaData() != null) return true;
			else return false;
		} catch (Exception e) {
			return false;
		}
	}
}